package com.wenwei.paper.base;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/15.
 */
public class AtyContainer {

    private AtyContainer() {
    }

    private static AtyContainer instance = new AtyContainer();
    public static List<Activity> activityStack = new ArrayList<Activity>();

    public int getActivitySize (){
        return activityStack.size();
    }

    public static AtyContainer getInstance() {
        return instance;
    }

    public void addActivity(Activity aty) {
        activityStack.add(aty);
    }

    public void removeActivity(Activity aty) {
        activityStack.remove(aty);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 弹出多个Activity
     */
    public void popActivity(int num){
        /**
         * 如果参数大于栈中activity数量，则num置为栈中activity数量
         */
        num = (activityStack.size()<num?activityStack.size():num);
        for(;num>0;num--){
            /**
             * 调用无参pop()弹出栈顶;
             */
            popActivity();
        }
    }

    /**
     * 弹出栈顶Activity
     */
    public void popActivity(){
        //如果已经到了栈底,显然需要退出程序
        boolean exitFlag=false;
        if(activityStack.size()==0){
            /*栈为空*/
            return;
        }else if(activityStack.size()==1) {
            /*到了栈底，应该退出App*/
            exitFlag=true;
        }
        //finish栈顶activity
        activityStack.get(activityStack.size()-1).finish();
        //在栈中移除栈顶
        activityStack.remove(activityStack.size()-1);
        //退出App
        if(exitFlag){
            System.exit(0);
        }
    }
}


